package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.msg.WmNewsDownOrUpMsg;
import com.heima.model.wemedia.dtos.WmNewsContentDto;
import com.heima.model.wemedia.dtos.WmNewsDownOrUpDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.nio.file.Watchable;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;


    @Override
    public PageResponseResult findPage(WmNewsPageReqDto dto) {
        if (WmThreadLocalUtil.getUser() == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        LambdaQueryWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaQuery()
                .eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId())
                .orderByDesc(WmNews::getPublishTime);

        //添加动态条件  文章状态
        if(dto.getStatus() != null){
            wrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //标题
        if(StringUtils.isNotEmpty(dto.getKeyword())){
            wrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //频道列表
        if(dto.getChannelId() != null){
            wrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //发布日期
        if(dto.getBeginPubDate() != null && dto.getEndPubDate() != null){
            wrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }

        Page<WmNews> page = page(new Page<>(dto.getPage(), dto.getSize()), wrapper);
        PageResponseResult result = new PageResponseResult((int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    @Override
    public void submit(WmNewsDto dto) {
        if (WmThreadLocalUtil.getUser() == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //拿到的是dto -> 数据库 WmNews
        WmNews wmNews = new WmNews();
        //解析出内容中的图片
        String content = dto.getContent(); //[{"type":"image","value":"http://192.168.200.130:9000/heima103/2022/08/20/a2beada3f3a54db9a5a9bb1c666f7b49.jpeg\"},{"type":"text",value":"测试文章3"}]
        List<String> contentImageUrls = getContentImageUrls(content);
        //是否是自动选择
        if(Objects.equals(dto.getType(),WemediaConstants.WM_NEWS_TYPE_AUTO)){
            int size = contentImageUrls.size();
            // >=3张 取前3张
            if(size >= 3){
                dto.setImages(contentImageUrls.subList(0,3)); //包头不包尾
                dto.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }else if(size >= 1){
                //1-2张 取第1张
                dto.setImages(contentImageUrls.subList(0,1));
                dto.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            }else{
                //0张就无图
                dto.setImages(null);
                dto.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
        }
        //拷贝 需要拷贝的字段类型完全相同
        BeanUtils.copyProperties(dto,wmNews);
        //特殊字段处理 image类型不一样
        if(dto.getImages() != null){
            //["1.jpg","2.jpg"] 集合转字符串 -> "1.jpg","2.jpg"
            wmNews.setImages(StringUtils.join(dto.getImages(),","));
        }
        //wmNews补充字段
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setSubmitedTime(new Date());
        if(dto.getId() == null){
            //新增逻辑
            wmNews.setCreatedTime(new Date());
            wmNews.setEnable((short) 1);

            save(wmNews);
        }else {
            //修改逻辑
            //删除当前这篇文章和所有图片的绑定关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            updateById(wmNews);
        }
        if(Objects.equals(dto.getStatus(),WmNews.Status.NORMAL.getCode())){
            //如果是草稿，直接返回，不去创建图片和文章的关联关系，草稿中的图片可以随便删除
            return;
        }
        //添加内容中的图片
        saveImagesAndNewsRelation(contentImageUrls,wmNews.getId(),WemediaConstants.WM_CONTENT_REFERENCE);
        //添加封面中的图片
        saveImagesAndNewsRelation(contentImageUrls,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);

        wmNewsAutoScanService.autoScan(wmNews);
    }

    @Override
    public void downOrUp(WmNewsDownOrUpDto dto) {
        Integer id = dto.getId();
        WmNews wmNews = getById(id);
        if(wmNews == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //是否发布
        if(!Objects.equals(wmNews.getStatus(),WmNews.Status.PUBLISHED.getCode())){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"文章类型不存在");
        }
        //判断状态是否一致
        if(Objects.equals(wmNews.getEnable(),dto.getEnable())){
            return;
        }
        //更新文章表的状态
        boolean update = update(Wrappers.<WmNews>lambdaUpdate()
                .eq(WmNews::getId, dto.getId())
                .eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId())
                .set(WmNews::getEnable, dto.getEnable())
        );
        if(!update){
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        //发消息
        WmNewsDownOrUpMsg msg = new WmNewsDownOrUpMsg();
        msg.setArticleId(wmNews.getArticleId());
        msg.setEnable(dto.getEnable());

        kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,
                JSON.toJSONString(msg));
    }


    private void saveImagesAndNewsRelation(List<String> imageUrls, Integer id, Short type) {
        //没有图片，不需要处理
        if(CollectionUtils.isEmpty(imageUrls)){
            return;
        }
        //查询url对应的id
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                .in(WmMaterial::getUrl, imageUrls)
                .select(WmMaterial::getId));
        //判断取出来的数据id是否数量一致
        if(wmMaterials.size() != imageUrls.size()){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"素材图片已经不存在");
        }

        List<Integer> ids = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());

        wmNewsMaterialMapper.saveBatchRelation(ids,id,type);
    }

    //获取内容中image字段中的value
    private List<String> getContentImageUrls(String content) {

        //反序列化 将字符串转成java对象
        List<WmNewsContentDto> wmNewsContentDtos = JSON.parseArray(content, WmNewsContentDto.class);

        //普通写法
//        HashSet<String> urls = new HashSet<>();
//        for (WmNewsContentDto wmNewsContentDto : wmNewsContentDtos) {
//            //比较 如果类型是image就将value添加到集合中
//            if(Objects.equals(wmNewsContentDto.getType(), WemediaConstants.WM_NEWS_TYPE_IMAGE)){
//                urls.add(wmNewsContentDto.getValue());
//            }
//        }
//        return new ArrayList<String>(urls);
        
        //stream流  起到过滤的效果 去除重复的图片
        List<String> collect = wmNewsContentDtos.stream()
                .filter(x -> Objects.equals(x.getType(), WemediaConstants.WM_NEWS_TYPE_IMAGE))
                .map(WmNewsContentDto::getValue).distinct().collect(Collectors.toList());
        return collect;
    }


}
